Why is the remove function not working for hashmaps? [migrated]
Posted
by
John Marston
on Programmers
See other posts from Programmers
or by John Marston
Published on 2012-10-24T23:20:47Z
Indexed on
2012/10/25
5:20 UTC
Read the original article
Hit count: 176
java
I am working on a simple project that obtains data from an input file, gets what it needs and prints it to a file. I am basically getting word frequency so each key is a string and the value is its frequency in the document. The problem however, is that I need to print out these values to a file in descending order of frequency. After making my hashmap, this is the part of my program that sorts it and writes it to a file.
//Hashmap I create
Map<String, Integer> map = new ConcurrentHashMap<String, Integer>();
//function to sort hashmap
while (map.isEmpty() == false){
for (Entry<String, Integer> entry: map.entrySet()){
if (entry.getValue() > valueMax){
max = entry.getKey();
System.out.println("max: " + max);
valueMax = entry.getValue();
System.out.println("value: " + valueMax);
}
}
map.remove(max);
out.write(max + "\t" + valueMax + "\n");
System.out.println(max + "\t" + valueMax);
}
When I run this i get:
t 9
t 9
t 9
t 9
t 9
....
so it appears the remove function is not working as it keeps getting the same value. I'm thinking i have an issue with a scope rule or I just don't understand hashmaps very well.
If anyone knows of a better way to sort a hashmap and print it, I would welcome a suggestion.
thanks
© Programmers or respective owner